package questions;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.*;

/**
 * execute最建议并且简单的还是推荐在run 自己处理
 * submit 执行期间的异常会收集起来，get时候触发
 *
 * 怎么收集异常信息到logger?
 * **1. 重写group行为
 * @see java.lang.ThreadGroup#uncaughtException(java.lang.Thread, java.lang.Throwable)
 * ** 重写afterExecute
 * @see ThreadPoolExecutor#afterExecute(java.lang.Runnable, java.lang.Throwable)
 */
@Slf4j
public class ExceptionInMultiThread {

    ExecutorService executorService= Executors.newFixedThreadPool(1);

    public static void main(String[] args) {

    }

    /**
     * Runnable 类型的异常
     */
    @Test
    public void testExecute(){

        try {
            executorService.execute(new MyRunnable());
        }catch (Exception e){
            log.error("+====这里无法catch");
            e.printStackTrace();
        }
    }
    static class MyRunnable implements Runnable{
        @Override
        public void run() {
            try {
                System.out.println(1 / 0);
            }catch (Exception e){
                log.error("这里能处理",e);
                throw e;
            }
        }
    }

    @Test
    public void test2(){
        Future<?> res = executorService.submit(new MyRunnable());
        log.info("{}",res.isDone());
        log.info("{}",res.isCancelled());

        try {
            //get 能够触发之前运行时的异常，可以做处理，比如记录
            res.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }


}
